#include "xLink.h"
#include "xInMappingPort.h"
#include "xOutMappingPort.h"
#include "xMappingNode.h"

#include <sstream>

std::string xLink::toMDString(MDSType type) {
		std::ostringstream MDSstr ;
		xMappingNode *leftparent = left->getParent();
		xMappingNode *rightparent = right->getParent();
		
		int leftsno, rightsno, leftindex, rightindex ;

		if (leftparent->getCompositeParent() != NULL) {
			// this is the case where a linke connect from a mapping node with a composite to other mapping node
			xMappingNode* cp = leftparent->getCompositeParent();
			leftsno = cp->getSerialNo();
			leftindex = cp->getOutportIndex(left);
		} else {
			leftsno = leftparent->getSerialNo();
			leftindex = left->getIndexOfParent();
		}

		if ( rightparent->getCompositeParent() != nullptr && rightparent->getType() == "gate") {
			// this is the case where a link connects from a mapping node to a gate node
			xMappingNode* cp = rightparent->getCompositeParent();
			rightsno = cp->getSerialNo();
			rightindex = cp->getInportIndex(right);
		} else {
			rightsno = rightparent->getSerialNo();
			rightindex = right->getIndexOfParent();	
		}

		if ( type == NormalMDSFormat ){
			MDSstr << "node "      << leftsno << " port " << leftindex 
				   << " to node "  << rightsno << " port " << rightindex << endl ;
		} else if ( type == ParameterizedMDSFormat ){
			std::ostringstream leftsNoString ;
			if ( left->getParent()->isForeachElements()){
				leftsNoString << "SN" << leftsno;
			} else {
				leftsNoString << leftsno;
			}

			std::ostringstream rightsNoString;
			if ( right->getParent()->isForeachElements()){
				rightsNoString << "SN" << rightsno;
			} else {
				rightsNoString << rightsno;
			}
			MDSstr << "ADD_LINK "  << "node "       << leftsNoString.str() << " port " << leftindex 
				   << " to node "  << rightsNoString.str() << " port " << rightindex << endl ;
		} else {
			assert(false);
		}

		return MDSstr.str();
}